import type { FC } from "react";
import { Breadcrumb } from "antd";
import classNames from "classnames";
import { matchRoutes } from "@/utils";
import { useMemo, useContext } from "react";
import type { BreadcrumbProps } from "antd";
import { useTranslation } from "react-i18next";
import { pathToRegexp } from "path-to-regexp";
import LayoutContext from "@/layout/Wrapper/context";
import { useLocation, Link } from "react-router-dom";

import styles from "./styles.module.less";

type BreadcrumbItems = BreadcrumbProps["items"];

interface IProps {
  lastTitle?: string;
}

const BasicBreadcrumb: FC<IProps> = (props) => {
  const { lastTitle } = props;
  const { t } = useTranslation();
  const { pathname } = useLocation();
  const { routes = [] } = useContext(LayoutContext);

  const matches = useMemo(() => {
    return matchRoutes(routes, pathname)
      .filter(item => !item.homeRoute);
  }, [routes]);

  const items = useMemo<BreadcrumbItems>(() => {
    return matches.map((item, i) => {
      let title = t(`menus.${item.name}`);
      const isLast = i + 1 === matches.length;
      if (isLast && lastTitle) title = lastTitle;
      return { key: item.path, title, path: item.path };
    });
  }, [matches]);

  return (
    <div className={styles.breadcrumb}>
      <Breadcrumb
        items={items}
        separator=">"
        itemRender={(route) => {
          let active = false;
          const path = route.path;
          if (path) {
            const reg = pathToRegexp(path, []);
            active = reg.test(pathname);
          }
          return (
            <Link
              reloadDocument={false}
              to={route.path ?? ''}
              children={route.title}
              className={classNames(
                styles.item,
                active && styles.active
              )}
            />
          )
        }}
      />
    </div>
  );
};

export default BasicBreadcrumb;
